package com.kaili.basic.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.mapper.*;
import com.kaili.basic.pojo.entity.*;
import com.kaili.basic.pojo.vo.BaseNewsVO;
import com.kaili.basic.service.BaseNewsService;
import com.kaili.common.util.CommonUtil;
import com.kaili.common.util.FastDFSClient;
import com.kaili.common.util.LoginDetailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: dxj
 * @descrinption: Created by dxj on 18-6-27.
 * @modified:
 */

@Service
public class BaseNewsServiceImpl implements BaseNewsService {

    @Autowired
    private GlobalClobMapper globalClobMapper;
    @Autowired
    private BaseNewsMapper newsMapper;
    @Autowired
    private BaseNewsRangeMapper newsRangeMapper;
    @Autowired
    private GlobalAttachmentMapper attachmentMapper;
    @Autowired
    private BasicSiteMapper basicSiteMapper;


    @Override
    public boolean addNews(BaseNewsIssueVO newsIssue,List<String> fileTypes,List<byte[]> byteList) {

        //这里要控制事物
        //生成大字段记录
        GlobalClob clob = new GlobalClob();
        clob.setClobValue(newsIssue.getClobValue());
        clob.setCreatedTime(new Date());
        globalClobMapper.addGlobalClob(clob);

        newsIssue.setCreatedBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        SimpleDateFormat date=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String a1=date.format(newsIssue.getIssueTime());//发布时间
        String a2=date.format(new Date());//当前时间
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
           Date dt1 = dateFormat.parse(a1);//发布时间
           Date dt2 = dateFormat.parse(a2);//当前时间
           // 发布时间小于当前时间就取当前时间;
           if(dt1.getTime()<dt2.getTime()){
               newsIssue.setIssueTime(new Date());
           }
        }catch (Exception e){

        }
        newsIssue.setSiteId(LoginDetailUtils.getSiteId().longValue());
        newsIssue.setCreatedTime(new Date());
        newsIssue.setReplyCount(0L);
        newsIssue.setIsRead(0L);
        newsIssue.setNewsClobId(clob.getClobId());
        newsIssue.setSeeCount(0L);
        newsIssue.setRdStatus(1);
        newsIssue.setNewsRangeMode(1);
        if (byteList != null && byteList.size() > 0){
            newsIssue.setBlAttachment(true);
        }else{
            newsIssue.setBlAttachment(false);
        }

        newsMapper.addNews(newsIssue);

        //添加发布范围
        if (newsIssue.getDataList() != null && newsIssue.getDataList().size() > 0){
            for (Long dateId : newsIssue.getDataList()
                 ) {
                BaseNewsRange newsRange = new BaseNewsRange();
                newsRange.setNewsId(newsIssue.getNewsId());
                newsRange.setDateId(dateId);
                newsRangeMapper.addNewsRange(newsRange);
            }
        }

        //附件的新增

        if (byteList != null && byteList.size() >0){
            for (int i = 0;i<byteList.size(); i++) {
                try{
//                    MultipartFile file = mediaList.get(i);
//                    String mediaName = file.getOriginalFilename();
                    String fileType = fileTypes.get(i);
//                            mediaName.lastIndexOf(".") != -1? StringUtils.substring(mediaName, mediaName.lastIndexOf(".") + 1, mediaName.length()):null;
                    //文件实际名称
                    String fileName = UUID.randomUUID().toString().replaceAll("-","")+fileType;
                    FastDFSClient client = new FastDFSClient("classpath:fds.properties");
                    //获取字节流，
                    byte[] in = byteList.get(i);
                    String uploadFile = client.uploadFile(in,fileType);
                    //上传图片完毕，创建附件
                    GlobalAttchment attchment = new GlobalAttchment();
                    attchment.setAttExt(fileType);
                    attchment.setAttSize(new Long((long)in.length));
                    attchment.setCreatedBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
                    attchment.setCreatedTime(new Date());
                    attchment.setDataType(1L);
                    attchment.setDataId(newsIssue.getNewsId());
                    attchment.setRdStatus(1);
                    attchment.setRealName(fileName);
                    attchment.setSiteId(newsIssue.getSiteId());
                    attchment.setRemark("通知发布创建附件");
                    attchment.setAttachmentPath(uploadFile);
                    attachmentMapper.addAttachment(attchment);
                }catch (Exception e){
                    System.out.println("图片上传失败"+e);
                    return false;
                }
            }
        }

        return true;
    }



    @Override
    public boolean ediNews(BaseNewsIssueVO newsIssue) {
        newsIssue.setModifiedBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        newsIssue.setModifiedTime(new Date());

        //根据ID查询通知
        BaseNewsIssueVO baseNewsIssue = newsMapper.getNewsIssueById(newsIssue.getNewsId());
        //查询大字段
        GlobalClob clob = globalClobMapper.getGlobalClobById(baseNewsIssue.getNewsClobId());
        //修改对应大字段
        clob.setClobValue(newsIssue.getClobValue());
        int clogFlag = globalClobMapper.ediGlobalClob(clob);
        if (clogFlag > 0){
            //修改发布范围开始
            List<Long> dataList = newsIssue.getDataList();
            //根据通知Id删掉原有发布范围
            newsRangeMapper.delNewsRangeByNewsId(newsIssue.getNewsId());
            //添加发布范围
            if (dataList != null && dataList.size() > 0){
                for (Long dateId : dataList
                        ) {
                    BaseNewsRange newsRange = new BaseNewsRange();
                    newsRange.setNewsId(newsIssue.getNewsId());
                    newsRange.setDateId(dateId);
                    newsRangeMapper.addNewsRange(newsRange);
                }
            }
            SimpleDateFormat date=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String a1=date.format(newsIssue.getIssueTime());//发布时间
            String a2=date.format(new Date());//当前时间
            DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            try {
                Date dt1 = dateFormat.parse(a1);//发布时间
                Date dt2 = dateFormat.parse(a2);//当前时间
                // 发布时间小于当前时间就取当前时间;
                if(dt1.getTime()<dt2.getTime()){
                    newsIssue.setIssueTime(new Date());
                }
            }catch (Exception e){

            }
            //修改发布范围结束
            int flag = newsMapper.ediNews(newsIssue);
            if (flag >0){
                return true;
            }else{
                return false;
            }
        }else {
            return false;
        }


    }

    @Override
    public BaseNewsIssueVO getNewsIssueById(Long newsId) {
        BaseNewsIssueVO issue = newsMapper.getNewsIssueById(newsId);
        return issue;
    }

    @Override
    public Page<BaseNewsVO> queryPagedList(Page<BaseNewsIssueVO> page, BaseNewsIssueVO newsIssue) {
        List<BaseNewsIssueVO> list = newsMapper.queryPagedList(page,newsIssue);

        for (BaseNewsIssueVO issue: list) {
            List<Long> siteIds = issue.getDataList();
            List<BaseSiteIdAndName> sites = new ArrayList<BaseSiteIdAndName>();
            //遍历发布网点ID集合，找到网点ID名字
            for (int i = 0 ; i< siteIds.size();i++){
                BasicSite site = basicSiteMapper.getBySiteId(siteIds.get(i));
                BaseSiteIdAndName siteIdAndName = new BaseSiteIdAndName();
                siteIdAndName.setValue(site.getSiteId());
                siteIdAndName.setLabel(site.getSiteName());
                sites.add(siteIdAndName);
            }
            issue.setSiteIdNames(sites);
        }

        Page<BaseNewsVO> newsVOPage = new Page<>(page.getCurrent(), page.getSize());
        newsVOPage.setRecords(CommonUtil.toList(list, BaseNewsVO.class));
        return newsVOPage;
    }


    //通知查询页面分页查询
    public Page<BaseNewsVO> queryForNews(Page<BaseNewsIssueVO> page, BaseNewsIssueVO newsIssue){
        List<BaseNewsIssueVO> list = newsMapper.queryForNews(page,newsIssue);
        Page<BaseNewsVO> newsVOPage = new Page<>(page.getCurrent(), page.getSize());
        newsVOPage.setRecords(CommonUtil.toList(list, BaseNewsVO.class));
        return newsVOPage;
    }


    //标题模糊查询
    public List<String> queryLikeTitle(String newsTitle){
        return newsMapper.queryLikeTitle(newsTitle);

    }

    //修改通知为已读
    public boolean ediNewsIsRead(BaseNewsIssueVO issue){
        issue.setModifiedBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        issue.setModifiedTime(new Date());
        int flag = newsMapper.ediNewsIsRead(issue);
        if (flag > 0){
            return true;
        }else {
            return false;
        }
    }

}
